package protobuf;/*

 */

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;

/**
 * @ClassName NettyClient
 * @Author Final
 * @Project DataStructures
 */
public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        //需要一个事件循环组
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();

        try {

            //创建一个启动对象
            //客户端使用的不是serverbootstrap，而是bootstrap
            Bootstrap bootstrap = new Bootstrap();

            /**
             * 设置相关参数
             *  1、设置线程组
             *  2、设置客户端通达的实现类
             */
            bootstrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //pipeline.addLast("ProtobufDecoder",new ProtobufDecoder());
                        }
                    })
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(new NettyClientHandler());//加入自己的处理器
                        }
                    });

            System.out.println("客户端 ok...");
            //启动客户端去连接服务端
            //关于channelFuture，涉及到netty的异步模型
            ChannelFuture sync = bootstrap.connect("127.0.0.1", 6668).sync();
            //给关闭通道进行监听
            sync.channel().closeFuture().sync();
        }finally {
            eventExecutors.shutdownGracefully();
        }

    }
}
